package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.dao.OrdersDao;
import com.itheima.reggie.entity.*;
import com.itheima.reggie.entity.dto.OrdersDto;
import com.itheima.reggie.service.*;
import com.itheima.reggie.utils.ThreadLocalUtil;
import com.itheima.reggie.web.R;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * @author Wq
 * @description 针对表【orders(订单表)】的数据库操作Service实现
 * @createDate 2022-08-20 18:25:05
 */
@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersDao, Orders>
        implements OrdersService {

    @Autowired
    private AddressBookService addressBookService;
    @Autowired
    private ShoppingCartService shoppingCartService;
    @Autowired
    private UserService userService;
    @Autowired
    private OrderDetailService orderDetailService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean sumitWithOrderDetail(OrdersDto ordersDto) {
        //核心业务
        //查询相关信息
        //查询当前用户
        Long userId = ThreadLocalUtil.getCurrentId();
        User user = userService.getById(userId);
        //查询购物车
        LambdaUpdateWrapper<ShoppingCart> lqw = new LambdaUpdateWrapper<>();
        lqw.eq(ShoppingCart::getUserId, userId);
        List<ShoppingCart> shoppingCartList = shoppingCartService.list(lqw);

        //雪花算法计算订单号
        long number = IdWorker.getId();
        //计算总金额
        AtomicInteger atomicInteger = new AtomicInteger(0);
        //封装订单明细
        List<OrderDetail> orderDetailList = shoppingCartList.stream().map(shoppingCart -> {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(shoppingCart, orderDetail, "user_id");
            orderDetail.setOrderId(number);
            BigDecimal amount = shoppingCart.getAmount();
            atomicInteger.addAndGet(amount.multiply(new BigDecimal(shoppingCart.getNumber())).intValue());
            return orderDetail;
        }).collect(Collectors.toList());

        //通过地址id查询
        AddressBook addressBook = addressBookService.getById(ordersDto.getAddressBookId());


        //创建订单对象
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersDto, orders);
        orders.setUserId(userId);
        orders.setNumber(number + "");
        orders.setStatus(2);
        orders.setCheckoutTime(LocalDateTime.now());
        orders.setOrderTime(LocalDateTime.now());
        orders.setPayMethod(ordersDto.getPayMethod());
        orders.setAmount(new BigDecimal(atomicInteger.get()));
        orders.setPhone(addressBook.getPhone());
        orders.setAddress(addressBook.getDetail());
        orders.setUserName(user.getName());
        orders.setConsignee(addressBook.getConsignee());
        orders.setRemark(ordersDto.getRemark());
        //保存订单实体
        this.save(orders);

        //保存订单明细
        orderDetailService.saveBatch(orderDetailList);
        //清空购物车
        shoppingCartService.remove(lqw);
        return true;
    }

    @Override
    public R page(Long pageNum, Long pageSize, Long number, String beginTime, String endTime) {
        Page<Orders> page = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<Orders> lqw = new LambdaQueryWrapper<>();
        //根据订单号查询
        lqw.eq(number != null, Orders::getNumber, number)
                //查询指定时间内的订单信息
                .between(beginTime != null || endTime != null, Orders::getOrderTime, beginTime, endTime)
                //根据下单时间待续排列
                .orderByDesc(Orders::getOrderTime);
        //执行分页查询
        this.page(page, lqw);
        return R.success("", page);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R again(Orders orders) {
        //获取当前登录用户id
        Long userId = ThreadLocalUtil.getCurrentId();
        //先清空购物车
        shoppingCartService.remove(Wrappers.lambdaQuery(ShoppingCart.class)
                .eq(ShoppingCart::getUserId, userId));
        //在加入购物车
        //获取订单id
        Long id = orders.getId();
        //通过id查询订单明细的对应的id
        Orders inDbOrders = this.getById(id);
        //查询订单明细
        String orderId = inDbOrders.getNumber();
        List<OrderDetail> orderDetailList = orderDetailService.list(Wrappers.lambdaQuery(OrderDetail.class)
                .eq(orderId != null, OrderDetail::getOrderId, orderId));
        //将这些数据加入购物车
        List<ShoppingCart> shoppingCartList = orderDetailList.stream().map(orderDetail -> {
            //创建购物车对象
            ShoppingCart shoppingCart = new ShoppingCart();
            BeanUtils.copyProperties(orderDetail, shoppingCart, "orderId", "id");
            shoppingCart.setUserId(userId);
            shoppingCart.setCreateTime(LocalDateTime.now());
            return shoppingCart;
        }).collect(Collectors.toList());

        //添加购物车
        boolean result = shoppingCartService.saveBatch(shoppingCartList);
        if (result) {
            return R.success("成功");
        }
        return R.success("失败");
    }
}




